package com.ruoyi.web.controller.normal;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.Bidi;
import java.util.Date;
import java.util.List;

import com.ruoyi.system.domain.ShopOrderItem;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ShopOrder;
import com.ruoyi.system.service.IShopOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.xml.crypto.Data;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2019-10-29
 */
@Controller
@RequestMapping("/normal/order")
public class ShopOrderController extends BaseController
{
    private String prefix = "normal/order";

    @Autowired
    private IShopOrderService shopOrderService;

    @RequiresPermissions("normal:order:view")
    @GetMapping()
    public String order()
    {
        return prefix + "/order";
    }

    /**
     * 查询订单列表
     */
    @RequiresPermissions("normal:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ShopOrder shopOrder)
    {
        startPage();
        List<ShopOrder> list = shopOrderService.selectShopOrderList(shopOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("normal:order:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ShopOrder shopOrder)
    {
        List<ShopOrder> list = shopOrderService.selectShopOrderList(shopOrder);
        ExcelUtil<ShopOrder> util = new ExcelUtil<ShopOrder>(ShopOrder.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 新增订单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订单
     */
    @RequiresPermissions("normal:order:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ShopOrder shopOrder)
    {
        return toAjax(shopOrderService.insertShopOrder(shopOrder));
    }

    /**
     * 修改订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ShopOrder shopOrder = shopOrderService.selectShopOrderById(id);
        mmap.put("shopOrder", shopOrder);

        List<ShopOrderItem> shopOrderItemList = shopOrder.getShopOrderItems();

        //Todo: 暂时所有的订单 只会有一个oderItem
        mmap.put("orderItem", shopOrderItemList.get(0));
        String strConsignee = StringUtils.EMPTY;
        try {
            if (StringUtils.isNotEmpty(shopOrder.getConsignee())){
                strConsignee = URLDecoder.decode(shopOrder.getConsignee(), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Integer status = shopOrder.getStatus().intValue();
        String strStatus = "";
        switch (status){
            case 0:
                strStatus = "代付款";
                break;
            case 3:
                strStatus = "已支付";
                break;
            case 5:
                strStatus = "已完成";
                break;
            case 13:
                strStatus = "已评价";
                break;
            case 10:
                strStatus = "正在退款";
                break;
            case 11:
                strStatus = "已退款";
                break;
            default:
                strStatus = "未知状态";
        }

        mmap.put("strStatus", strStatus);
        mmap.put("consignee", strConsignee);

        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("normal:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ShopOrder shopOrder)
    {
        Long id = shopOrder.getId();
        String strAddress = shopOrder.getAddress();
        String strMemo = shopOrder.getMemo();
        String strConsignee = shopOrder.getConsignee();
        String strPhone = shopOrder.getPhone();

        ShopOrder actualShopOrder = shopOrderService.selectShopOrderById(id);
        if (actualShopOrder == null){
            return AjaxResult.error("参数错误,请联系管理员");
        }

        actualShopOrder.setMemo(strMemo);
        actualShopOrder.setAddress(strAddress);
        actualShopOrder.setPhone(strPhone);
        actualShopOrder.setConsignee(strConsignee);
        actualShopOrder.setModifyDate(new Date());

        return toAjax(shopOrderService.updateShopOrder(actualShopOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("normal:order:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(shopOrderService.deleteShopOrderByIds(ids));
    }


    /**
     * 修改订单金额
     */
    @RequiresPermissions("normal:order:changeAmount")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @GetMapping( "/changeAmount/{id}")
    public String changeAmount(@PathVariable("id") Long id, ModelMap mmap)
    {
        if (id == null){
            return "/404";
        }
        ShopOrder shopOrder = shopOrderService.selectShopOrderById(id);
        mmap.put("order", shopOrder);
        return prefix + "/changeOrderAmount";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("normal:order:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/changeAmountSave")
    @ResponseBody
    public AjaxResult changeAmountSave(ShopOrder shopOrder)
    {
        Long id = shopOrder.getId();
        ShopOrder actualShopOrder = shopOrderService.selectShopOrderById(id);
        if (actualShopOrder == null){
            return AjaxResult.error("发送的参数异常,请联系管理员");
        }

        BigDecimal changeAmount = BigDecimal.valueOf(shopOrder.getOffsetAmount());
        BigDecimal payAmount = BigDecimal.valueOf(actualShopOrder.getAmount());
        if (payAmount.add(changeAmount).compareTo(BigDecimal.ZERO) < 1){
            return AjaxResult.error("修改金额和支付金额的合,不能小或等于0");
        }

        actualShopOrder.setOffsetAmount(changeAmount.doubleValue());
        return toAjax(shopOrderService.updateShopOrder(actualShopOrder));
    }
}
